﻿using UnityEngine;
using System.Collections;

public class GameLobby : MonoBehaviour {
	public int width;
	public int height;
	public NetworkManager networkManager;

	bool connecting = false;
	string roomName = "I wanna";
	public void OnGUI() {
		GUI.BeginGroup (new Rect((Screen.width - width) / 2, 
			(Screen.height - height) / 2, width, height));
			GUI.Box(new Rect(0, 0, width, height), "Game Lobby");
			if (networkManager.isRefreshing) {
				GUI.Label(new Rect(30, 30, 200, 30), "Retrieving a list of running games");
			} else if (networkManager.hostData == null || networkManager.hostData.Length == 0) {
				GUI.Label(new Rect(30, 30, 200, 30), "Find no running games");
			} else {
				HostData[] hostData = networkManager.hostData;
				GUILayout.BeginArea(new Rect(30, 30, 500, 200));
					for (int i = 0; i < hostData.Length; i++) {
						GUI.Label(new Rect(0, 40 * i, 200, 20),  hostData[i].gameName);
						if (GUI.Button(new Rect(400, 40 * i, 100, 20), "Join")) {
							Debug.Log("Connect to " + hostData[i]);
							networkManager.ConnectToServer(i);
							connecting = true;
						}
					}
				GUILayout.EndArea();
			}
			GUILayout.BeginArea(new Rect(30, height - 40, width, 40));
				GUILayout.BeginHorizontal();
					if (GUILayout.Button("Refresh List",  GUILayout.Width(100))) {
						networkManager.RefreshHostList();
					}
					roomName = GUILayout.TextField(roomName, GUILayout.Width(300));
					if (GUILayout.Button("Create Game",  GUILayout.Width(100))) {
						networkManager.StartServer(roomName);
						Application.LoadLevel("baseScene");
					}
				GUILayout.EndHorizontal();
			if (connecting) {
				GUILayout.Label("Connecting");
			}
	        GUILayout.EndArea();
		GUI.EndGroup();
	}
	void OnFailedToConnect(NetworkConnectionError error) {
        Debug.Log("Could not connect to server: " + error);
        connecting = false;
    }
    void OnConnectedToServer() {
        Debug.Log("Connected to server");
		Application.LoadLevel("baseScene");
		connecting = false;
    }
}
